package com.capacitydorm.server.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.capacitydorm.server.common.util.JWTUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
@Component
public class JwtFilter extends GenericFilterBean {

    @Override
    public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
            throws IOException, ServletException {

        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;
        final String authHeader = request.getHeader("token");
        final String uri = request.getRequestURI();


        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "token,Content-Type");
        response.setHeader("Access-Control-Expose-Headers", "*");
        System.out.println("OK!!!!!");
        System.out.println(uri);
        if ("OPTIONS".equals(request.getMethod())) {
            System.out.println("OPTIONS");
            response.setStatus(HttpServletResponse.SC_OK);

            chain.doFilter(req, res);
        } else {
            if(uri.contains("/login")){
                System.out.println("1111111111111111111111111111111111111111111111111111111111111");
                chain.doFilter(request, response);
                return;
            }
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                throw new ServletException("未登录，请登录");
            }

            //如果请求路径是公用的
            final String token = authHeader.substring(7);
            try {
//                final Claims claims = Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody();
                final String claims = JWTUtil.getUsername(token);
                request.setAttribute("claims", claims);
            } catch (final SignatureException e) {

                throw new ServletException("登录错误或失效");
            } catch (Exception e) {
                e.printStackTrace();
            }
//            chain.doFilter(request, response);

            chain.doFilter(request, response);
        }
    }
}
